package ai.people.core.plugin.command;

import ai.people.core.plugin.listener.JarListenerFactory;
import ai.people.netmon.utils.StringUtils;
import lombok.RequiredArgsConstructor;
import org.apache.commons.io.monitor.FileAlterationMonitor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.io.File;
import java.util.Arrays;
import java.util.Objects;

/**
 * jar侦听器
 *
 * @author yuanqinglong
 * @date 2022/6/13 19:08
 */
@Component
@RequiredArgsConstructor
public class JarListenerRunner implements CommandLineRunner {

    private final Logger logger = LoggerFactory.getLogger(JarListenerRunner.class);

    private final JarListenerFactory fileListenerFactory;


    /**
     * Callback used to run the bean.
     *
     * @param args incoming main method arguments
     * @throws Exception on error
     */
    @Override
    public void run(String... args) {
        //项目启动时检查已存在的jar包并加载
        if(StringUtils.isNotBlank(fileListenerFactory.getPluginProperties().getDir())){
            File file = null;
            try{
                file = new File(fileListenerFactory.getPluginProperties().getDir());
            }catch (Exception e){
                logger.error("配置的jar包监听目录不存在，请检查【plugin.listener.dir】配置项");
                e.printStackTrace();
            }
            if(file != null && file.isDirectory() && file.listFiles() != null && file.listFiles().length > 0){
                for (File listFile : Objects.requireNonNull(file.listFiles())) {
                    fileListenerFactory.getJarListener().onFileCreate(listFile);
                }
            }
        }

        // 创建jar包变更监听者
        FileAlterationMonitor fileAlterationMonitor = fileListenerFactory.getMonitor();
        try {
            // do not stop this thread
            fileAlterationMonitor.start();
        } catch (Exception e) {
            logger.error("文件监听器启动失败", e);
        }
    }
}
